<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView || isCheck || postForm.status==='已批准'"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <el-col :span="12">
            <div class="postInfo-container">
              <el-row>
                <el-form-item
                  label-width="180px"
                  label="仪器预约:"
                  prop="machineId"
                >
                  <el-select
                    v-model="postForm.machineId"
                    :remote-method="getMachinelist"
                    filterable
                    remote
                    placeholder="请选择仪器预约"
                    :loading="loading"
                    @change="changeMachine"
                  >
                    <el-option
                      v-for="item in machineListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  label-width="180px"
                  label="预约起始时间:"
                  prop="dateRange"
                >
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="To"
                    start-placeholder="请选择开始时间"
                    end-placeholder="请选择结束时间"
                    :picker-options="pickerOptions"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  label-width="180px"
                  label="申请人:"
                  prop="requestorId"
                >
                  <el-select
                    v-model="postForm.requestorId"
                    :remote-method="getRequestorList"
                    filterable
                    remote
                    placeholder="请选择申请人"
                    :loading="loading"
                    @change="changeRequestor"
                  >
                    <el-option
                      v-for="item in requestorListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="requestorPhone"
                  label-width="180px"
                  label="申请人电话："
                >
                  <el-input
                    v-model="postForm.requestorPhone"
                    :maxlength="100"
                    name="name"
                    :disabled="true"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="requestorEmail"
                  label-width="180px"
                  label="申请人邮箱："
                >
                  <el-input
                    v-model="postForm.requestorEmail"
                    :maxlength="100"
                    name="name"
                    :disabled="true"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
            </div>
          </el-col>

          <el-col :span="12">
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="approverName"
                label-width="180px"
                label="审批人："
              >
                <el-input
                  v-model="postForm.approverName"
                  :maxlength="100"
                  name="name"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="approverPhone"
                label-width="180px"
                label="审批人电话："
              >
                <el-input
                  v-model="postForm.approverPhone"
                  :maxlength="100"
                  name="name"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="approverEmail"
                label-width="180px"
                label="审批人邮箱："
              >
                <el-input
                  v-model="postForm.approverEmail"
                  :maxlength="100"
                  name="name"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="status"
                label-width="180px"
                label="状态："
              >
                <el-input
                  v-model="postForm.status"
                  :maxlength="100"
                  name="name"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item
                style="margin-bottom: 40px"
                prop="approveTime"
                label-width="180px"
                label="审批时间："
              >
                <el-input
                  v-model="postForm.approveTime"
                  :maxlength="100"
                  name="name"
                  :disabled="true"
                >
                </el-input>
              </el-form-item>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <div style="margin-top: 40px;">
      <el-button
        v-if="!isView && !isCheck"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
      <el-button
        v-if="isCheck"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="approveAppointment(true)"
      >
        批准
      </el-button>
      <el-button
        v-if="isCheck"
        v-loading="loading"
        style="margin-left: 50px; width: 100px"
        type="success"
        @click="approveAppointment(false)"
      >
        驳回
      </el-button>
    </div>
  </div>
</template>

<script>
import { fetchUserList, fetchUserById } from "@/api/user";
import { fetchActiveMachineList } from "@/api/machine";
import {
  fetchMachineAppointmentById,
  createMachineAppointment,
  updateMachineAppointment,
  fetchAppliedMachineAppointmentById,
} from "@/api/machine-appointment";
import { generateNewDate } from '@/utils/date';
import { mapGetters } from "vuex";

const defaultForm = {
  machineId: "", // 仪器预约ID
  machineName: "", // 仪器预约名称
  machineStartDate: "", // 预约起始时间
  machineEndDate: "", // 预约结束时间
  requestorId: "", // 申请人ID
  requestorName: "", // 申请人姓名
  requestorPhone: "", // 申请人电话
  requestorEmail: "", // 申请人邮箱
  status: "待审批", // 状态: 待审批，已批准，驳回
  approverId: null, // 审批人ID
  approverName: "", // 审批人姓名
  approverPhone: "", // 审批人电话
  approverEmail: "", // 审批人邮箱
  approveTime: null, // 预约审核时间
  id: undefined,
};

export default {
  name: "MachineAppointmentDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
    isCheck: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      dateRange: [],
      machineList: [],
      appliedMachineList: [],
      machineListOptions: [],
      userList: [],
      requestorListOptions: [],
      formatDate: null,
      pickerOptions: {
        disabledDate: this.disabledDate,
        onPick: this.pick,
      },
      rules: {
        machineId: [{ required: true, validator: validateRequire }],
        dateRange: [{ required: true, validator: validateRequire }],
        requestorId: [{ required: true, validator: validateRequire }],
      },
    };
  },
  computed: {
    ...mapGetters(["id"]),
  },
  created() {
    this.getUsers();
    this.getMachines();
    if (this.isEdit || this.isView || this.isCheck) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
    if (this.isCheck) {
      this.getApprover();
    }
  },
  methods: {
    getUsers() {
      this.listLoading = true;
      fetchUserList().then((res) => {
        this.userList = res.data.map((item) => {
          return {
            label: item.userName,
            value: item.id,
            phone: item.userCellphone,
            email: item.userEmail,
          };
        });
        this.requestorListOptions = this.userList;

        this.listLoading = false;
      });
    },
    getApprover() {
      this.listLoading = true;
      fetchUserById(this.id).then((res) => {
        this.postForm.approverId = res.data[0].id;
        this.postForm.approverName = res.data[0].userName;
        this.postForm.approverPhone = res.data[0].userCellphone;
        this.postForm.approverEmail = res.data[0].userEmail;
        this.listLoading = false;
      });
    },
    getMachines() {
      this.listLoading = true;
      fetchActiveMachineList().then((res) => {
        this.machineList = res.data.map((item) => {
          return { label: item.machineName, value: item.id };
        });
        this.machineListOptions = this.machineList;

        this.listLoading = false;
      });
    },
    getRequestorList(query) {
      if (query !== "") {
        this.loading = true;
        this.requestorListOptions = userList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.requestorListOptions = userList;
      }
    },
    getMachinelist(query) {
      if (query !== "") {
        this.loading = false;
        this.machineListOptions = machineList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.machineListOptions = machineList;
      }
    },
    pick({ maxDate, minDate }) {
      this.fromDate = minDate;
      this.postForm.machineStartDate = minDate;
      this.postForm.machineEndDate = maxDate;
    },
    disabledDate(date) {
      if (date < new Date(Date.now()).setHours(0, 0, 0, 0)) return true;
      if (this.appliedMachineList.length > 0) {
        for (const item of this.appliedMachineList) {
          if (date >= new Date(item.machineStartDate).setHours(0, 0, 0, 0) && 
            date <= new Date(item.machineEndDate).setHours(0, 0, 0, 0)
          ) {
            return true;
          }
        }
      }
      if (this.fromDate) {
        if (this.fromDate > date) {
          return true;
        } else {
          if (this.appliedMachineList.length > 0) {
            for (const item of this.appliedMachineList) {
          if (this.fromDate < new Date(item.machineStartDate).setHours(0, 0, 0, 0) && 
            date > new Date(item.machineStartDate).setHours(0, 0, 0, 0)
          ) {
            return true;
          }
        }
        }
        }
      }
      return false;
    },
    changeRequestor(val) {
      const selectedItem = this.userList.find((item) => {
        return item.value === val;
      });
      this.postForm.requestorName = selectedItem.label;
      this.postForm.requestorPhone = selectedItem.phone;
      this.postForm.requestorEmail = selectedItem.email;
    },
    changeMachine(val) {
      this.postForm.machineName = this.machineList.find((item) => {
        return item.value === val;
      }).label;
      fetchAppliedMachineAppointmentById(this.id).then((appliedRes) => {
        this.appliedMachineList = appliedRes.data;
      })
    },
    fetchData(id) {
      fetchMachineAppointmentById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.dateRange = [
            this.postForm.machineStartDate,
            this.postForm.machineEndDate,
          ];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    approveAppointment(isApprove) {
      if (isApprove) {
        this.postForm.status = "已批准";
      } else {
        this.postForm.status = "驳回";
      }
      this.postForm.approveTime = generateNewDate();
      this.submitForm();
    },
    submitForm() {
      this.$refs.postForm.validate((valid) => {
        if (!this.postForm.machineStartDate || !this.postForm.machineEndDate) {
          this.$message({
            message: "请选择预约时间段",
            type: "error",
          });
        }
        if (valid) {
          this.loading = true;
          if (this.postForm.id) {
            updateMachineAppointment(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/machineappointment/list");
                  this.$message({
                    title: "成功",
                    message: "仪器预约信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "仪器预约信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            createMachineAppointment(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/machineappointment/list");

                  this.$message({
                    title: "成功",
                    message: "仪器预约创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "仪器预约创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("仪器预约信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}
</style>
